package ofpof.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ofpof.service.SecurityService;
import ofpof.web.form.LoginForm;
import ofpof.web.validator.LoginFormValidator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class LoginController {
	
	@Autowired
	private LoginFormValidator loginFormValidator;
	
	@Autowired
	private SecurityService securityService;
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String showLogin(ModelMap modelMap) {
		
		if (securityService.isLoggedIn()) {
			return "redirect:../issues/all";
		}
		modelMap.put("loginForm",new LoginForm());
		return "login";
	}
	
	@RequestMapping(value="/login",method = RequestMethod.POST)
	public String doLogin(@ModelAttribute("loginForm") LoginForm loginForm, BindingResult bindingResult,HttpServletResponse response) {
		loginFormValidator.validate(loginForm, bindingResult);
		
		if (bindingResult.hasErrors()) {
			return "login";
		}
		
		boolean success = securityService.loginUser(loginForm,response);
		
		if (!success) {
			bindingResult.reject("login.failed");
			return "login";
		}
		
		 return "redirect:../issues/all"; 
	}
	
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String doLogout(HttpServletRequest request,HttpServletResponse response) {
		securityService.logout(request,response);
		return "redirect:../issues/all";
	}
	
	


}
